package src.origintrail;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.io.*;

import src.origintrail.Player.Pace;
import src.origintrail.Player.Rations;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
/**
 * Generates a UI for Moving the player
 * @author cassidy
 *
 */
public class ModuleMove 
{
	private JButton move;
	private JButton moveOne;
	private JButton cancel;
	private JButton shop;
	private static JLabel next;
	private JButton changeRations;
	private JButton changePace;
	private static JLabel distanceTraveled;
	private static JLabel distanceLeft;
	private static JLabel foodRemaining;
	private static JLabel rationLevel;
	private static JLabel speed;
	private static JLabel location;
	private static JLabel notify;
	private static JLabel date;
	private static JPanel info;
	private static JPanel note;
	public static final MapPanel mpanel = new MapPanel();
	private ButtonListener listener;
	private static Map map;
	public static boolean leaving;
        private static boolean rHit = false;

	/**
	 * Runs the operations for moving the player
	 */
	public void run()
	{	
		OriginTrail.uiPanel.setVisible(true);
		OriginTrail.animPanel.setVisible(true);
		OriginTrail.animPanel.removeAll();
		map = OriginTrail.plr.getMap();
		OriginTrail.animPanel.setPreferredSize(new Dimension(640,480));
		OriginTrail.infoPanel.setPreferredSize(new Dimension(640,100));
		OriginTrail.uiPanel.setPreferredSize(new Dimension(640,70));
		OriginTrail.uiPanel.removeAll();
		OriginTrail.otFrame.setPreferredSize(new Dimension(640,650));
		OriginTrail.infoPanel.setLayout(new BorderLayout());	
		OriginTrail.uiPanel.setLayout(new GridLayout(2,3));
		OriginTrail.animPanel.add(mpanel);
		info = new JPanel();
		note = new JPanel();
		info.setLayout(new GridLayout(3,3));		
		distanceTraveled = new JLabel("Distance Traveled: " + map.distanceTraveled());
		distanceLeft = new JLabel("Distance Remaining: " + map.getDistanceToNext());
		foodRemaining = new JLabel("Food Remaining: " + OriginTrail.plr.bags.find(new Food().initialize(0)).stack);
		location = new JLabel("Location: " + map.getCurrentLocation());
		rationLevel = new JLabel("Ration Level: " + OriginTrail.plr.getFoodSpeed());
		speed = new JLabel("Speed: " + OriginTrail.plr.getWagonSpeed());
		notify = new JLabel("Notifications: ");
		listener = new ButtonListener();
		move = new JButton("Move");
		moveOne = new JButton("Move One");
		cancel = new JButton("Save/Load");
		shop = new JButton("Shop for Supplies");
		date = new JLabel("Date: " + OriginTrail.plr.getDate());
		shop.addActionListener(listener);
		changeRations = new JButton("Change Rations");
		changePace = new JButton("Change Pace");
		changeRations.addActionListener(listener);
		changePace.addActionListener(listener);
		move.addActionListener(listener);
		moveOne.addActionListener(listener);
		cancel.addActionListener(listener);
		OriginTrail.uiPanel.removeAll();
		OriginTrail.uiPanel.add(move);
		OriginTrail.uiPanel.add(moveOne);
		OriginTrail.uiPanel.add(cancel);
		OriginTrail.uiPanel.add(changeRations);
		OriginTrail.uiPanel.add(changePace);
		OriginTrail.uiPanel.add(shop);
		info.add(distanceTraveled);
		info.add(distanceLeft);
		info.add(location);
		info.add(date);
		info.add(foodRemaining);
		info.add(rationLevel);
		info.add(speed);


		note.add(notify);

		OriginTrail.infoPanel.add(info, BorderLayout.CENTER);
		OriginTrail.infoPanel.add(note,BorderLayout.SOUTH);
		OriginTrail.otFrame.pack();

		//OriginTrail.infoPanel.setLayout(new SpringLayout());	
		//OriginTrail.uiPanel.setLayout(new BorderLayout());
		//		if(map.hasShop() == true)
		//		{
		//	leaving = false;
		//			while(!leaving){
		//				System.out.print("");
		//			}

		//}


	}
	/**
	 * gives the player the option of changing pace
	 */
	private void askPace() {

		OriginTrail.uiPanel.removeAll();
		OriginTrail.infoPanel.removeAll();
		TextListener textl = new TextListener();
		next = new JLabel("Select Pace");
		JButton[] paces = new JButton[Pace.values().length];
		JPanel pacePanel = new JPanel();
		ButtonGroup pacebutton = new ButtonGroup();
		for(int i = 0; i < paces.length; i++){
			paces[i] = new JButton(Pace.class.getEnumConstants()[i].name);
			paces[i].addActionListener(textl);
			pacebutton.add(paces[i]);
			pacePanel.add(paces[i]);
		}
		pacebutton.clearSelection();
		OriginTrail.uiPanel.add(pacePanel,BorderLayout.WEST);
		OriginTrail.uiPanel.add(next);
		OriginTrail.otFrame.pack(); 
	}
	/**
	 * gives the player options for rations
	 */
	private void askRations()
	{
		OriginTrail.uiPanel.removeAll();
		OriginTrail.infoPanel.removeAll();
		RationListener rat = new RationListener();
		next = new JLabel("Select Rations");
		JButton[] rations = new JButton[Rations.values().length];
		JPanel rationPanel = new JPanel();
		ButtonGroup rationbutton = new ButtonGroup();
		for(int i = 0; i < rations.length; i++){
			rations[i] = new JButton(Rations.class.getEnumConstants()[i].name);
			rations[i].addActionListener(rat);
			rationbutton.add(rations[i]);
			rationPanel.add(rations[i]);
		}

		OriginTrail.uiPanel.add(rationPanel, BorderLayout.WEST);
		OriginTrail.uiPanel.add(next);
		OriginTrail.otFrame.pack();

	}


	/**
	 * waits for an action event to occur and responds accordingly
	 * @author cassidy
	 *
	 */
	private class ButtonListener implements ActionListener
	{
		@Override
		public void actionPerformed(ActionEvent e) 
		{
			String notes = "";
			if(e.getSource().equals(move))
			{
				if(map.hasRiver()){
				}
				else if(!map.isEnd())
				{
					map.move();
				}


			}
			else if(e.getSource().equals(moveOne))
			{
				if(map.hasRiver()){
				}
				else if(!map.isEnd())
				{
					map.moveOne();
				}

			}
			else if(e.getSource().equals(cancel))
			{
				System.out.println("*BOOP*");
					JFrame j = new JFrame();
					String s = "SAVE OR LOAD?";
					j.getContentPane().setLayout(new BoxLayout(j.getContentPane(), BoxLayout.Y_AXIS));
					JButton save = new JButton("Save");
					JButton load = new JButton("Load");
					save.addActionListener(new SaveListener(j, "save.sav"));
					load.addActionListener(new LoadListener(j, "save.sav"));
					j.add(new JLabel(s));
					j.add(save);
					j.add(load);
					j.pack();
					j.setVisible(true);
			}
			else if(e.getSource().equals(changeRations))
			{
				leaving = true;
				askRations();
			}
			else if(e.getSource().equals(changePace))
			{
				leaving = true;
				askPace();

			}
			else if(e.getSource().equals(shop) && map.hasShop())
			{
				OriginTrail.uiPanel.remove(move);
				OriginTrail.uiPanel.remove(moveOne);
				OriginTrail.uiPanel.remove(shop);
				OriginTrail.uiPanel.remove(cancel);
				OriginTrail.uiPanel.remove(changePace);
				OriginTrail.uiPanel.remove(changeRations);
				OriginTrail.uiPanel.removeAll();
				OriginTrail.infoPanel.removeAll();
				EvtSpawner.instance.spawnShopEvent();

				ModuleMove.leaving = true;
				try {
					EvtSpawner.instance.getHandler().pop().activate();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			redoLabels();
			if(map.isEnd())
			{
				OriginTrail.uiPanel.remove(move);
				OriginTrail.uiPanel.remove(moveOne);
				OriginTrail.uiPanel.remove(shop);
				OriginTrail.uiPanel.remove(cancel);
				OriginTrail.uiPanel.remove(changePace);
				OriginTrail.uiPanel.remove(changeRations);
				EvtSpawner.instance.spawnEndEvent();	
				try {
					EvtSpawner.instance.getHandler().pop().activate();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
			else if(map.hasShop() && (e.getSource().equals(move)) || e.getSource().equals(moveOne) && map.distance()==0)
			{
				mpanel.updatePosition();
				notes = "You are at a waypoint. Feel free to grab supplies at the shop!";
			}
			if(map.hasRiver()){
                            if(!rHit)
                                new RiverFrame().init();
                            rHit = true;
                        }else
                            rHit = false;
			notify.setText("Notifications: " + notes);

		}


	}

        public static void renote(String string) {
            notify.setText("Notifications: " + string);
        }

        public static void redoLabels() {
            distanceTraveled.setText("Distance Traveled: " + map.distanceTraveled());
            distanceLeft.setText(("Distance Remaining: " + map.getDistanceToNext()));
            foodRemaining.setText("Food Remaining: " + OriginTrail.plr.bags.find(new Food().initialize(0)).stack);
            rationLevel.setText("Ration Level: " + OriginTrail.plr.getFoodSpeed());
            location.setText("Location: " +  map.getCurrentLocation());
            date.setText("Date: " + OriginTrail.plr.getDate());
        }
	/** 
	 * class that listens for the user selecting a radio button for Pace Selection
	 * @author cassidy
	 *
	 */
	private class TextListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {

			for(int i = Pace.values().length-1; i>=0; i--)
			{

				if(Pace.values()[i].name().equalsIgnoreCase(e.getActionCommand()))
				{
					OriginTrail.plr.setWagonSpeed(Pace.values()[i]);
				}            	
			}
			run();
			System.out.println("hi");
		}
	}
	/**
	 * class that listens for the user selecting a radio button for Ration selection
	 * @author cassidy
	 *
	 */
	private class RationListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {

			for(int i = Rations.values().length-1; i>=0; i--)
			{

				if(Rations.values()[i].name().equalsIgnoreCase(e.getActionCommand()))
				{
					OriginTrail.plr.setFoodSpeed(Rations.values()[i]);
				}            	
			}

			run();
		}

	}
	private class SaveListener implements ActionListener{


		JFrame parent;
                String saveName;

		public SaveListener(JFrame j, String s) {
			parent = j;
                        saveName = s;
		}

		@Override
		public void actionPerformed(ActionEvent e)
		{
			//saving shit here chris fix this
			File savefile = new File(saveName);
			String fff;
			
			try {
					
			if (!savefile.exists())
			{
				savefile.createNewFile();
				
			}
			else {
				savefile.delete();
				savefile.createNewFile();
			}
			FileWriter fstream = new FileWriter(saveName);
			BufferedWriter out = new BufferedWriter(fstream);
			//map
			//inventory
			//player

			//map info
			fff = Integer.toString(OriginTrail.plr.getMap().distance());
			out.write(fff, 0, fff.length());
			out.newLine();
			fff = Integer.toString(OriginTrail.plr.getMap().distanceTraveled());
			out.write(fff, 0, fff.length());
			out.newLine();
			out.write(OriginTrail.plr.getMap().getCurrentLocation(), 0, OriginTrail.plr.getMap().getCurrentLocation().length());
			out.newLine();
                        out.write(Integer.toString(ModuleMove.mpanel.getCount()), 0, Integer.toString(ModuleMove.mpanel.getCount()).length());
                        out.newLine();
			//should i save the hasShop or hasRiver? or would that be useless. 
			//which of the above are useless anyway, you can prob. delete them

			//inventory
			//HELP HOW I TOKENIZE INVENTORY CHRIS FIX THIS okay this might work (YES it works) (i think)
				int n = OriginTrail.plr.bags.contents.size();
				Item k;
				for(int i = 0; i < n ; i++) {
					k = (Item)OriginTrail.plr.bags.contents.get(i);
					fff = k.getName();
					out.write(fff, 0, fff.length());
					out.newLine();
					fff = Integer.toString(k.getStack());
					out.write(fff, 0, fff.length()); 
					out.newLine(); }
			
				out.write("EOI", 0, 3);
				out.newLine();

			//player
			//what do i even need to save from player
			// name, day, month, partynames, class i guess
				out.write (OriginTrail.plr.getName(), 0, OriginTrail.plr.getName().length());
				out.newLine();
				fff = Integer.toString(OriginTrail.plr.getDay());
				out.write (fff, 0, fff.length());
				out.newLine();
				fff = Integer.toString(OriginTrail.plr.getMonth());
				out.write (fff, 0, fff.length());
				out.newLine();
				
				int m = OriginTrail.plr.getParty().length;
				PartyMember[] pt = OriginTrail.plr.getParty();
				for (int j = 0; j < m; j++)
				{
					System.out.println(pt[j].getName());
					out.write(pt[j].getName(), 0, pt[j].getName().length());
					out.newLine();
				}
				//still need to save class
				
				out.write("EOF", 0, 3);


			out.close();
			} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			parent.dispose();
		}


	}

	private class LoadListener implements ActionListener{


		JFrame parent;
                String saveFile;

		public LoadListener(JFrame j, String s) {
			parent = j;
                        saveFile = s;
		}

		@Override
		public void actionPerformed(ActionEvent e) {
                    try {
                        FileInputStream loadstream = new FileInputStream(saveFile);
                        DataInputStream in = new DataInputStream(loadstream);
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        String strLine;

                        strLine = br.readLine();
                        OriginTrail.plr.getMap().setDistanceToNext(Integer.parseInt(strLine));
                        strLine = br.readLine();
                        OriginTrail.plr.getMap().setDistanceTraveled(Integer.parseInt(strLine));
                        strLine = br.readLine();
                        for(int i = 0; i < OriginTrail.plr.getMap().size(); i++)
                            if(OriginTrail.plr.getMap().get(i).getName().equals(strLine))
                                OriginTrail.plr.getMap().setLocation(i);
                        strLine = br.readLine();
                        ModuleMove.mpanel.setCount(Integer.parseInt(strLine));
                        OriginTrail.plr.bags.contents.removeAll(OriginTrail.plr.bags.contents);
                        strLine = br.readLine();
                        while(!"EOI".equals(strLine)){
                            int intLine = Integer.parseInt(br.readLine());
                            OriginTrail.plr.bags.addItem(((Item)Class.forName("src.origintrail." + strLine).newInstance()).initialize(intLine));
                            strLine = br.readLine();
                        }
                        strLine = br.readLine();
                        OriginTrail.plr.setName(strLine);
                        strLine = br.readLine();
                        OriginTrail.plr.setMonth(Integer.parseInt(strLine));
                        strLine = br.readLine();
                        OriginTrail.plr.setDay(Integer.parseInt(strLine));
                        strLine = br.readLine();
                        ArrayList l = new ArrayList();
                        while(!"EOF".equals(strLine)){
                            strLine = br.readLine();
                            l.add(new PartyMember(strLine));
                        }
                        //EOF
                        //COOL WRAP IT UP LOADAILURES

                        in.close();
                        OriginTrail.otFrame.repaint();
                        ModuleMove.redoLabels();
                    } catch (Exception ex) {
                        Logger.getLogger(ModuleMove.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    parent.dispose();
		}


	}
        
        

}


